import wechatValidate from 'wechat-validate'
Page({
  behaviors: [wechatValidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '', // 展示的选中的房屋名称
    houseId: '', // 提交选中房屋id
    name: '', // 姓名
    gender: 1, // 性别
    mobile: '', //手机号
    visitDate: '', //访问日期
    currentDate: +new Date(), // 当前时间
    maxDate: +new Date() + 3 * 24 * 60 * 60 * 1000, // 最大时间
  },
  rules: {
    houseId: [{ required: true, message: '请选择房屋' }],
    name: [
      { required: true, message: '请填写访客姓名' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: '请填写中文访客姓名' },
    ],
    mobile: [
      { required: true, message: '请填写手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号' },
    ],
    visitDate: [{ required: true, message: '请选择到访日期' }],
  },
  async onShow() {
    const { data: houseList } = await wx.http.get('/house')
    this.setData({ houseList })
  },
  // 选中房屋
  selectHouse(ev) {
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name,
    })
  },
  // 房屋的动作面板
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  // 访问日期的动作面板
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 点击确获取选中的日期
  confirm(ev) {
    this.setData({
      visitDate: wx.utils.dateFormat(ev.detail),
    })
    this.closeDateLayer()
  },
  async goPassport() {
    // 1. 预校验
    if (!this.validate()) return
    // 2. 发送请求
    const { houseId, name, mobile, visitDate, gender } = this.data
    const {
      data: { id },
    } = await wx.http.post('/visitor', { houseId, name, mobile, visitDate, gender })
    // 3. 跳转
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
